<?php
/**
 * 轮播图管理API
 * 提供轮播图的增删改查功能
 */

require_once '../../utils/Database.php';
require_once '../../utils/Response.php';
require_once '../../config/database.php';

class CarouselManagement {
    private $db;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    /**
     * 获取轮播图列表
     */
    public function getCarousels() {
        $page = max(1, intval($_GET['page'] ?? 1));
        $limit = min(50, max(1, intval($_GET['limit'] ?? 10)));
        $offset = ($page - 1) * $limit;
        
        $status = $_GET['status'] ?? '';
        $search = $_GET['search'] ?? '';
        
        try {
            $sql = "SELECT id, title, image_url, link_type, link_value, sort, status, 
                           view_count, click_count, created_at, updated_at 
                    FROM carousels 
                    WHERE 1=1";
            
            $params = [];
            
            if ($status) {
                $sql .= " AND status = ?";
                $params[] = $status;
            }
            
            if ($search) {
                $sql .= " AND title LIKE ?";
                $params[] = "%$search%";
            }
            
            $sql .= " ORDER BY sort ASC, id DESC LIMIT $limit OFFSET $offset";
            
            $carousels = $this->db->fetchAll($sql, $params);
            
            // 获取总数
            $countSql = str_replace("SELECT id, title, image_url, link_type, link_value, sort, status, view_count, click_count, created_at, updated_at", "SELECT COUNT(*) as total", $sql);
            $countSql = preg_replace('/ORDER BY.*LIMIT.*/', '', $countSql);
            $total = $this->db->fetchOne($countSql, $params)['total'];
            
            Response::success([
                'list' => $carousels,
                'pagination' => [
                    'page' => $page,
                    'limit' => $limit,
                    'total' => intval($total),
                    'pages' => ceil($total / $limit)
                ]
            ]);
            
        } catch (Exception $e) {
            Response::error('获取轮播图列表失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取轮播图详情
     */
    public function getCarousel($id) {
        if (empty($id)) {
            Response::error('轮播图ID不能为空');
        }
        
        try {
            $sql = "SELECT * FROM carousels WHERE id = ?";
            $carousel = $this->db->fetchOne($sql, [$id]);
            
            if (!$carousel) {
                Response::error('轮播图不存在', 404);
            }
            
            Response::success($carousel);
            
        } catch (Exception $e) {
            Response::error('获取轮播图详情失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 创建轮播图
     */
    public function createCarousel() {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $title = trim($input['title'] ?? '');
        $imageUrl = trim($input['image_url'] ?? '');
        $linkType = $input['link_type'] ?? 'none';
        $linkValue = trim($input['link_value'] ?? '');
        $sort = intval($input['sort'] ?? 0);
        $status = $input['status'] ?? 'active';
        
        // 验证必填字段
        if (empty($title)) {
            Response::error('轮播图标题不能为空');
        }
        
        if (empty($imageUrl)) {
            Response::error('轮播图图片不能为空');
        }
        
        // 验证状态值
        if (!in_array($status, ['active', 'inactive'])) {
            Response::error('状态值无效');
        }
        
        // 验证链接类型
        if (!in_array($linkType, ['none', 'url', 'page', 'miniprogram'])) {
            Response::error('链接类型无效');
        }
        
        try {
            $data = [
                'title' => $title,
                'image_url' => $imageUrl,
                'link_type' => $linkType,
                'link_value' => $linkValue,
                'sort' => $sort,
                'status' => $status,
                'view_count' => 0,
                'click_count' => 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            
            $id = $this->db->insert('carousels', $data);
            
            if ($id) {
                Response::success(['id' => $id], '轮播图创建成功');
            } else {
                Response::error('轮播图创建失败');
            }
            
        } catch (Exception $e) {
            Response::error('创建轮播图失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 更新轮播图
     */
    public function updateCarousel($id) {
        if (empty($id)) {
            Response::error('轮播图ID不能为空');
        }
        
        $input = json_decode(file_get_contents('php://input'), true);
        
        // 验证轮播图存在
        $existing = $this->db->fetchOne("SELECT id FROM carousels WHERE id = ?", [$id]);
        if (!$existing) {
            Response::error('轮播图不存在', 404);
        }
        
        $updateData = ['updated_at' => date('Y-m-d H:i:s')];
        
        // 只更新提供的字段
        if (isset($input['title'])) {
            $title = trim($input['title']);
            if (empty($title)) {
                Response::error('轮播图标题不能为空');
            }
            $updateData['title'] = $title;
        }
        
        if (isset($input['image_url'])) {
            $imageUrl = trim($input['image_url']);
            if (empty($imageUrl)) {
                Response::error('轮播图图片不能为空');
            }
            $updateData['image_url'] = $imageUrl;
        }
        
        if (isset($input['link_type'])) {
            if (!in_array($input['link_type'], ['none', 'url', 'page', 'miniprogram'])) {
                Response::error('链接类型无效');
            }
            $updateData['link_type'] = $input['link_type'];
        }
        
        if (isset($input['link_value'])) {
            $updateData['link_value'] = trim($input['link_value']);
        }
        
        if (isset($input['sort'])) {
            $updateData['sort'] = intval($input['sort']);
        }
        
        if (isset($input['status'])) {
            if (!in_array($input['status'], ['active', 'inactive'])) {
                Response::error('状态值无效');
            }
            $updateData['status'] = $input['status'];
        }
        
        try {
            $result = $this->db->update('carousels', $updateData, 'id = :id', ['id' => $id]);
            
            if ($result) {
                Response::success(null, '轮播图更新成功');
            } else {
                Response::error('轮播图更新失败');
            }
            
        } catch (Exception $e) {
            Response::error('更新轮播图失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 删除轮播图
     */
    public function deleteCarousel($id) {
        if (empty($id)) {
            Response::error('轮播图ID不能为空');
        }
        
        try {
            // 验证轮播图存在
            $existing = $this->db->fetchOne("SELECT id FROM carousels WHERE id = ?", [$id]);
            if (!$existing) {
                Response::error('轮播图不存在', 404);
            }
            
            $result = $this->db->delete('carousels', 'id = ?', [$id]);
            
            if ($result) {
                // 同时删除相关的点击记录
                $this->db->delete('carousel_clicks', 'carousel_id = ?', [$id]);
                Response::success(null, '轮播图删除成功');
            } else {
                Response::error('轮播图删除失败');
            }
            
        } catch (Exception $e) {
            Response::error('删除轮播图失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 批量更新排序
     */
    public function updateSort() {
        $input = json_decode(file_get_contents('php://input'), true);
        $items = $input['items'] ?? [];
        
        if (empty($items)) {
            Response::error('排序数据不能为空');
        }
        
        try {
            $this->db->getConnection()->beginTransaction();
            
            foreach ($items as $item) {
                $id = intval($item['id'] ?? 0);
                $sort = intval($item['sort'] ?? 0);
                
                if ($id > 0) {
                    $this->db->update('carousels', 
                        ['sort' => $sort, 'updated_at' => date('Y-m-d H:i:s')], 
                        'id = :id', 
                        ['id' => $id]
                    );
                }
            }
            
            $this->db->getConnection()->commit();
            Response::success(null, '排序更新成功');
            
        } catch (Exception $e) {
            $this->db->getConnection()->rollBack();
            Response::error('更新排序失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取轮播图统计信息
     */
    public function getStats() {
        try {
            $stats = [];
            
            // 总数统计
            $totalSql = "SELECT 
                            COUNT(*) as total,
                            SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
                            SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive,
                            SUM(view_count) as total_views,
                            SUM(click_count) as total_clicks
                         FROM carousels";
            
            $stats = $this->db->fetchOne($totalSql);
            
            // 今日点击统计
            $todayClicksSql = "SELECT COUNT(*) as today_clicks FROM carousel_clicks WHERE DATE(clicked_at) = CURDATE()";
            $todayClicks = $this->db->fetchOne($todayClicksSql);
            $stats['today_clicks'] = $todayClicks['today_clicks'];
            
            Response::success($stats);
            
        } catch (Exception $e) {
            Response::error('获取统计信息失败: ' . $e->getMessage());
        }
    }
}

// 处理请求
$carouselMgmt = new CarouselManagement();

$method = $_SERVER['REQUEST_METHOD'];
$pathInfo = $_SERVER['PATH_INFO'] ?? '';
$action = $_GET['action'] ?? '';

switch ($method) {
    case 'GET':
        if ($action === 'stats') {
            $carouselMgmt->getStats();
        } elseif (!empty($_GET['id'])) {
            $carouselMgmt->getCarousel($_GET['id']);
        } else {
            $carouselMgmt->getCarousels();
        }
        break;
        
    case 'POST':
        if ($action === 'sort') {
            $carouselMgmt->updateSort();
        } else {
            $carouselMgmt->createCarousel();
        }
        break;
        
    case 'PUT':
        if (empty($_GET['id'])) {
            Response::error('缺少轮播图ID');
        }
        $carouselMgmt->updateCarousel($_GET['id']);
        break;
        
    case 'DELETE':
        if (empty($_GET['id'])) {
            Response::error('缺少轮播图ID');
        }
        $carouselMgmt->deleteCarousel($_GET['id']);
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>